package com.huanzhidadi.singleweb.delayqueue;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.DelayQueue;

@Data
@Slf4j
@AllArgsConstructor
public class DelayQueueConsumer implements Runnable {

    private DelayQueue<DelayedUser> delayQueue;

    private Integer messageCount;

    // 为Thread结束提供标记
    private boolean stopFlag;

    @Override
    public void run() {
        int size = delayQueue.size();
        log.info("delayQueue: " + size);
        // 消费者一直保持
        if (0 == size) {
            stopFlag = true;
            return;
        }
        // 不能在这里用delayQueue.size()，因为delayQueue.take()以后，队列的元素数量变少了
        for (int i=0; i<size; i++) {
            try {
                DelayedUser delayedUser = delayQueue.take();
                log.info("take {}", delayedUser);
            } catch (Exception e) {
                log.error("消费者发生异常。", e);
            }
        }
        //stopFlag = true;
    }
}
